const { ipcRenderer } = window.electronApi
const { getStream } = require('../../utils/peer-control')
const { mouseDownType } = require('../../utils/enum')

const video = document.getElementById('screen-video')
// 获取桌面id
ipcRenderer.invoke('update:sourceId').then(async (sourceId) => {
    const stream = await getStream(sourceId) // 获取桌面流
    play(stream)
})

// 播放流
function play(stream) {
    video.srcObject = stream
    video.onloadedmetadata = (e) => video.play()
}

let { width: videoWidth, height: videoHeight } = video.getBoundingClientRect()

// 操作傀儡端
video.addEventListener('mousedown', (e) => {
    if (!videoWidth || !videoHeight) {
        videoWidth = video.getBoundingClientRect().width
        videoHeight = video.getBoundingClientRect().height
    }
    operationFn('mousedown', {
        type: mouseDownType[e.button],
        pageX: e.pageX,
        pageY: e.pageY,
        videoWidth,
        videoHeight
    })
})
window.addEventListener('keydown', (e) => {
    operationFn('keydown', {
        altKey: e.altKey,
        ctrlKey: e.ctrlKey,
        metaKey: e.metaKey,
        shiftKey: e.shiftKey,
        keyCode: e.keyCode
    })
})

const operationFn = (type, data) => {
    ipcRenderer.send('robot', type, data)
}